package util;


import java.util.HashMap;
import java.util.StringJoiner;

public class JSON {

    public static HashMap<String, Integer> jsonToHashMap(String json) {
        json=json.replaceAll("\\{","");
        json=json.replaceAll("}","");
        json=json.replaceAll("\"","");
        String[] nodes = json.split(",");

        HashMap<String, Integer> jsonMap=new HashMap<>(nodes.length);
        for (String node :nodes) {
            int split = node.indexOf(':');
            String key = node.substring(0,split).trim();
            String value = node.substring(split+1).trim();
            jsonMap.put(key,Integer.parseInt(value.trim()));
        }
        return jsonMap;
    }


    public static String HashMapToJson(HashMap<String, Integer> bookSelf) {
        StringJoiner sj=new StringJoiner(",","{","}");
        for (String key : bookSelf.keySet()) {
            String value=String.valueOf(bookSelf.getOrDefault(key,0));
            sj.add(String.format("\"%s\":\"%s\"",key,value));
        }
        System.out.println("bookSelf -> JSON"+sj);
        return sj.toString();
    }
}
